/*
 * @Author: huangyingli
 * @Date: 2023-02-23 11:37:11
 * @LastEditors: huangyingli
 * @LastEditTime: 2023-02-28 13:49:42
 * @Description:
 */
/**
 *
 * @param {string} path
 * @param {boolean} restore
 */
function pathHandle(path, restore) {
  if (restore) {
    path = path.replace(/$/g, '\\');
  } else {
    path = path.replace(/\\/g, '$');
  }
  return path;
}

// ************** node执行指令方法 *******************
// ==处理 child_process 输出中文乱码==
const iconv = require('iconv-lite');
const encoding = 'cp936';
const binaryEncoding = 'binary';
// ==处理 child_process 输出中文乱码==
const process = require('child_process');
const path = require('path');
let res, rej;
function execHandle(cmd) {
  const promise = new Promise((resolve, reject) => {
    res = resolve;
    rej = reject;
  });
  process.exec(cmd, { encoding: binaryEncoding }, (err, stdout, stderr) => {
    const out = iconv.decode(new Buffer(stdout, binaryEncoding), encoding);
    const outErr = iconv.decode(new Buffer(stderr, binaryEncoding), encoding);
    if (err || stderr) {
      rej(outErr || err);
    } else {
      res(out);
    }
  });

  return promise;
}
// *********************************

//

const allowNull = (required) => (!required ? '' : 'NOT NULL');

const isEmpty = (data) => {
  if (!data) return true;
  if (typeof data !== 'object') return true;
  return Object.keys(data).length === 0;
};

/**
 * 扁平数组树形化
 * @param {Array} data
 */
function toTree(data) {
  let result = [];
  data.forEach((d) => {
    d.key = d.id;
    if (d.parentId) {
      let parent = data.find((m) => m.id === d.parentId);
      if (parent) {
        parent.children = parent.children || [];
        parent.children.push(d);
      }
    } else {
      result.push(d);
    }
  });

  return result;
}

const { Base64 } = require('js-base64');
function unique(...args) {
  let base64s = args.map((arg) => Base64.encode(arg.toString()).toString());
  return base64s.join('');
}

const fs = require('fs');
const { nameTransform } = require('./response');
const { camel } = require('naming-style');
const log = require('../log4js');
function createPage(modalId, components, cb) {
  // 首先读取页面模板文件
  // 先写入 modalId
  // 写入 import
  // 写入 组件名称
  fs.readFile(
    path.resolve(__dirname, '../template/template.js'),
    (err, data) => {
      if (err) {
        console.log('错误', err);
        return;
      }
      console.log('数据', modalId, components);
      let template = data.toString();
      console.log('template', template);
      template = template.replace('#modalId#', modalId);
      let importArr = [];
      let componentArr = [];
      components.forEach((c) => {
        let importStr = `import ${c.name} from '@/components/${c.codeFileName}'`;
        let componentStr = `<${c.name} value={props?.componentsData?.${camel(
          c.name
        )}[0]} columnList={props?.columnList}></${c.name}>`;

        importArr.push(importStr);
        componentArr.push(componentStr);
      });

      template = template.replace('#imports#', importArr.join('; \n'));
      template = template.replace('#components#', componentArr.join(' \n'));

      // 将这个文件写入Next
      fs.mkdir(
        `E:\\myTestProject\\cms-nextjs\\src\\pages\\${modalId}`,
        { recursive: true },
        (err) => {
          if (err) {
            console.log('文件夹创建失败', err);
            return;
          }
          fs.writeFile(
            `E:\\myTestProject\\cms-nextjs\\src\\pages\\${modalId}\\[route].js`,
            template,
            (err) => {
              console.log('文件写入错误', err);
              cb();
            }
          );
        }
      );
    }
  );
}

// function moveComponet(path, name) {
//   let res, rej;
//   const promise = new Promise((resolve, reject) => {
//     res = resolve;
//     rej = reject;
//   });

//   fs.readFile(
//     __dirname,
//     `../uploadFile/${path}`,
//     { encoding: 'buffer' },
//     function (err, data) {
//       if (err) {
//         rej(err);
//       } else {
//         fs.writeFile(
//           `E:\\myTestProject\\cms-nextjs\\src\\components\\${name}`,
//           data,
//           (err) => {
//             if (err) {
//               console.log('文件写入错误', err);
//               rej(err);
//             } else {
//               res();
//             }
//           }
//         );
//       }
//     }
//   );
//   return promise;
// }

async function copyComponent(path, name) {
  return execHandle(
    `copy E:\\myTestProject\\cms-server\\uploadFile\\${path} E:\\myTestProject\\cms-nextjs\\src\\components\\${name}`
  ).then((stdout) => {
    log.info(`文件 ${name} 复制成功: `, stdout);
    return true;
  });
}

module.exports = {
  pathHandle,
  execHandle,
  allowNull,
  isEmpty,
  toTree,
  unique,
  createPage,
  // moveComponet,
  copyComponent,
};

// execHandle(`cd ${path.resolve('../component/src')} && del /s/q "*"`).then(
//   (stdout) => {
//     console.log(stdout);
//   }
// );

// execHandle(
//   'cd .. && copy .\\uploadFile\\upload_1d48c457c8d30d44d670b116bc6be449 .\\component\\src\\my.png'
// );

// let tree = toTree([
//   {
//     id: 1,
//     name: 'xxx',
//   },
//   {
//     id: 2,
//     parent: 1,
//     name: 'yyy',
//   },
//   {
//     id: 3,
//     name: 'zzz',
//   },
// ]);

// console.log(JSON.stringify(tree))

// console.log(unique('xx', 'x'))
